import pygame
import random

# 初始化pygame
pygame.init()

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600

# 蛇身块大小和移动速度
BLOCK_SIZE = 20
SPEED = 5

# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

# 时钟控制
clock = pygame.time.Clock()

# 字体设置
#font = pygame.font.SysFont(None, 48)
#选择支持中文的字体，否则窗口中显示乱码
font = pygame.font.Font('C:\Windows\Fonts\msyh.ttc', 32)

def draw_snake(snake_list):
    for block in snake_list:
        pygame.draw.rect(screen, GREEN, [block[0], block[1], BLOCK_SIZE, BLOCK_SIZE])

def show_text(text, color, x, y):
    text_surface = font.render(text, True, color)
    screen.blit(text_surface, (x, y))

def game_loop():
    game_over = False
    game_close = False

    # 初始位置和移动方向
    x = WINDOW_WIDTH / 2
    y = WINDOW_HEIGHT / 2
    dx = 0
    dy = 0

    snake_list = []
    snake_length = 1

    # 生成食物位置
    food_x = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
    food_y = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
    
    while not game_over:
        while game_close:
            
            #等待重新开始或退出情况下，监听关闭按钮事件，如果点击了关闭按钮，则退出游戏
            if event.type == pygame.QUIT:
                game_close = False
                game_over = True
            
            screen.fill(BLACK)
            show_text("按q退出，c重新开始，请切换输入法为英文状态", RED, 100, WINDOW_HEIGHT/2 - 50)
            pygame.display.update()
            
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        print('replaying...')
                        game_loop()

        if not game_close:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_over = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT and dx != BLOCK_SIZE:
                        dx = -BLOCK_SIZE
                        dy = 0
                    elif event.key == pygame.K_RIGHT and dx != -BLOCK_SIZE:
                        dx = BLOCK_SIZE
                        dy = 0
                    elif event.key == pygame.K_UP and dy != BLOCK_SIZE:
                        dy = -BLOCK_SIZE
                        dx = 0
                    elif event.key == pygame.K_DOWN and dy != -BLOCK_SIZE:
                        dy = BLOCK_SIZE
                        dx = 0
                    elif event.key == pygame.K_q:
                        game_close = True


        # 边界检测
        if x >= WINDOW_WIDTH or x < 0 or y >= WINDOW_HEIGHT or y < 0:
            game_close = True

        x += dx
        y += dy
        screen.fill(BLACK)
        pygame.draw.rect(screen, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
        
        snake_head = []
        snake_head.append(x)
        snake_head.append(y)
        snake_list.append(snake_head)

        if len(snake_list) > snake_length:
            del snake_list[0]

        # 自碰检测
        for block in snake_list[:-1]:
            if block == snake_head:
                game_close = True

        draw_snake(snake_list)
        show_text(f"得分: {snake_length-1}", WHITE, 10, 10)
        pygame.display.update()

        # 吃到食物
        if x == food_x and y == food_y:
            food_x = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
            food_y = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
            snake_length += 1

        clock.tick(SPEED)

    pygame.quit()
    quit()

# 启动游戏
game_loop()